//
//  KImageView.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/6/30.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class KImageView: MSView {
    
    var image:NSImage? {
        didSet {
            guard let img = image else {
                self.title.isHidden = false
                self.imageV.isHidden = true
                return
            }
            self.title.isHidden = true
            self.imageV.isHidden = false
            self.imageV.image = img
        }
    }
    
    convenience init(text:String,image:NSImage?) {
        self.init()
        self.text = text
        self.image = image
        self.setupUI()
        self.loadData()
    }
    
    func loadData()  {
        let newText = text[0]
        self.title.stringValue = newText
        
        guard let img = self.image else {
            self.title.isHidden = false
            self.imageV.isHidden = true
            return
        }
        self.title.isHidden = true
        self.imageV.isHidden = false
        self.imageV.image = img
    }
    
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var text:String = "" {
        didSet {
            let newText = text[0]
            self.title.stringValue = newText
            let color = JkColor.first(with: newText.firstLetter()) ?? NSColor.init(white: 0.1, alpha: 1.0)
            self.layer?.backgroundColor = color.cgColor
        }
    }
    
    func setupUI() {
        self.wantsLayer = true
        
        self.addSubview(title)
        title.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    lazy var title: NSLabel = {
        let lab = NSLabel.label(title: "", textColor: NSColor.white, font: NSFont.systemFont(ofSize: 14))
        lab.sizeToFit()
        lab.alignment = .center
        return lab
    }()
    
    lazy var imageV: NSImageView = {
        let imageV = NSImageView.init(image: NSImage.image(name:"icon_setting_audio")!)
        imageV.lineBreakMode = .byCharWrapping
        return imageV
    }()
}
